package com.woniuxy.java102vuecli.service.impl;

import com.woniuxy.java102vuecli.entity.Menu;
import com.woniuxy.java102vuecli.entity.Role;
import com.woniuxy.java102vuecli.entity.RoleMneuVO;
import com.woniuxy.java102vuecli.mapper.RoleMapper;
import com.woniuxy.java102vuecli.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author author
 * @Create 2023-10-08 17:26
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Override
    public List<Role> getAllRoles() {
        return roleMapper.selectAllRoles();
    }

    @Override
    public List<Integer> getMidsByRid(int rid) {
        List<Menu> menus = roleMapper.selectMenussByRid(rid);
//        List<Integer> mids=new ArrayList<>();
//        for(Menu menu :menus ){
//            mids.add(menu.getMid());
//        }
        List<Integer> mids=new ArrayList<>();
        //匿名内部类：接口的实现类对象
//        menus.forEach(new Consumer<Menu>() {
//            @Override
//            public void accept(Menu menu) {
//                mids.add(menu.getMid());
//            }
//        });
        //Lambda就是匿名内部类特殊情况的简写JDK1.8新语法（语法糖）
        //自动推断
//        menus.forEach(menu -> mids.add(menu.getMid()));
        //List<Menu>---->Stream<Menu>
        return menus.stream()
                //map   Stream<Menu>--->Stream<Integer>
                .map(menu -> menu.getMid())
                //终结操作，收集成List<String>
                .collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void allocationMenu(RoleMneuVO roleMenuVo) {
        //删除当前角色的所有已经分配的菜单
        roleMapper.deleteMenusByRid(roleMenuVo.getRole().getRid());
//        if(true){
//            throw new RuntimeException("角色分配菜单异常");
//        }
        //添加新的菜单
        roleMapper.insertMeuesByRid(roleMenuVo.getRole().getRid(),roleMenuVo.getMids());
    }
}
